package stackAndQueue;

import java.util.Iterator;

public class ResizingArrayStack<Item> implements Iterable<Item> {

    private Item[] a;
    private int N;

    public ResizingArrayStack() {
        a = (Item[]) new Object[1];
        N = 0;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    public void push(Item item) {
        a[N++] = item;
        if (N == a.length) resize(N * 2);
    }

    public Item pop() {
        if (N <= 0) {
            System.out.println("栈里无元素,无法出栈");
            return null;
        }
        Item item = a[--N];
        a[N] = null;
        if (N == a.length / 4) resize(a.length / 2);
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iterator<Item>() {
            private int i = N;

            @Override
            public boolean hasNext() {
                return i != 0;
            }

            @Override
            public Item next() {
                return a[--i];
            }
        };
    }
}
